# +----------------------------------------------------------------------
# | Pink [ A modern python web framework ]
# +----------------------------------------------------------------------
# | Copyright (c) 2023 http:#unnnnn.com All rights reserved.
# +----------------------------------------------------------------------
# | Author: chenjianhua <unnnnn@foxmail.com>
# +----------------------------------------------------------------------

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    # from cleo import Application as CommandApplication
    # from cleo import Command
    from cleo.application import Application as CommandApplication
    from cleo.commands.command import Command


class CommandCapsule:
    def __init__(self, command_application: "CommandApplication"):
        self.command_application = command_application
        self.commands = []
        self.command_name = []

    def add(self, *commands: "Command") -> "CommandCapsule":
        """Register new commands in the application."""
        # print(commands)
        #self.commands
        for command in commands:
            #command_name = command.config.name
            if command in self.commands:
                continue
            #self.command_name.append(command_name)
            self.commands.append(command)
            self.command_application.add(command)
        return self

    def swap(self, command: "Command") -> None:
        """Swap an (existing) command with the given one."""
        command_name = command.config.name
        # if command with same name has been registered remove it
        if self.command_application.find(command_name):
            # no public API to do this yet
            del self.command_application._commands[command_name]
        self.add(command)

    def run(self):
        """Run the cleo application."""
        return self.command_application.run()
